package com.sh.data.engine.domain.dataquality.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.common.util.DateUtil;
import com.sh.data.engine.domain.dataquality.model.domain.*;
import com.sh.data.engine.domain.dataquality.service.*;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.repository.dao.dataquality.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tinglan.ys
 * @description:
 * @date 2022/2/15 下午6:14
 */
@Service
@Slf4j
public class DataQualityViewServiceImpl implements DataQualityViewService {

    @Autowired
    private DataQualityStatisticsExceptionService dataQualityStatisticsExceptionService;

    @Autowired
    private DataQualityStatisticsMonitorService dataQualityStatisticsMonitorService;

    @Autowired
    private DataQualityStatisticsTableExceptionService dataQualityStatisticsTableExceptionService;

    @Autowired
    private DataQualityJobService dataQualityJobService;

    @Autowired
    private DataQualityJobRuleFieldService dataQualityJobRuleFieldService;

    @Autowired
    private DataQualityJobRuleService dataQualityJobRuleService;

    @Autowired
    private DataQualityRuleService dataQualityRuleService;

    private final Map<Integer, String> PROBLEM_MAP = new HashMap<>();

    private static final Integer DAYS_OF_TEND = 6;

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @PostConstruct
    public void init() {
        //    PROBLEM_MAP.put(0, "数据完整性");
        //    PROBLEM_MAP.put(1, "数据准确性");
        //    PROBLEM_MAP.put(2, "数据一致性");
        //    PROBLEM_MAP.put(3, "数据及时性");

        PROBLEM_MAP.put(0, "数据完整性");
        PROBLEM_MAP.put(1, "数据准确性");
        PROBLEM_MAP.put(2, "数据唯一性");
        PROBLEM_MAP.put(3, "数据有效性");
        PROBLEM_MAP.put(4, "其他");
    }

    @Override
    public List<DataQualityDistributeDomain> dataQualityDisTypeService(
        Integer timeType, Long projectId) {
        List<DataQualityViewDisModelDaoDomain> problemDis;
        if (timeType == null) {
            throw new BusinessException("时间类型参数为空");
        }
        switch (timeType) {
            case 0:
                problemDis = this.listProblemDisByDay(projectId);
                break;
            case 1:
                problemDis = this.listProblemDisByWeek(projectId);
                break;
            case 2:
                problemDis = this.listProblemDisByMonth(projectId);
                break;
            default:
                log.error("参数timeType有误,0 - day 、1 - week 、3 - month");
                throw new BusinessException("参数出错,请修改成（0 、1、2）");
        }

        // * 这里对数据进行处理，全值（sql返回进行排序，尽量配对次数为常量级别），缺值和为空做补0操作
        List<DataQualityDistributeDomain> responsesRes = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : PROBLEM_MAP.entrySet()) {
            boolean flag = true;
            for (DataQualityViewDisModelDaoDomain dataQualityViewDisModel : problemDis) {
                Integer type = dataQualityViewDisModel.getCategory();
                if (null != type && type.equals(entry.getKey())) {
                    flag = false;
                    responsesRes.add(
                        new DataQualityDistributeDomain(
                            entry.getValue(), dataQualityViewDisModel.getExceptionSum()));
                }
            }
            if (flag) {
                responsesRes.add(new DataQualityDistributeDomain(entry.getValue(), 0));
            }
        }
        return responsesRes;
    }

    @Override
    public DataQualityViewTableDomain dataQualityTableService(Long projectId) {
        DataQualityViewTableModelDaoDomain problemTableInfo = this.getProblemTableInfo(projectId);
        if (problemTableInfo == null) {
            log.info("未找到监控当日数据的表信息");
            problemTableInfo = new DataQualityViewTableModelDaoDomain();
        }
        // 所有表
        Integer allTable = problemTableInfo.getAllTable();
        // 监控表
        Integer monitorTable = problemTableInfo.getMonitorTable();
        // 所有字段
        Integer monitorField = problemTableInfo.getMonitorField();
        // 带描述的条数
        Integer descCount = problemTableInfo.getDescCount();
        // 未带描述的条数
        Integer noDescCount = problemTableInfo.getNoDescCount();

        allTable = allTable == null ? 0 : allTable;
        monitorTable = monitorTable == null ? 0 : monitorTable;
        monitorField = monitorField == null ? 0 : monitorField;
        descCount = descCount == null ? 0 : descCount;
        noDescCount = noDescCount == null ? 0 : noDescCount;

        NumberFormat numberFormat = NumberFormat.getInstance();
        // 保留0位小数
        numberFormat.setMaximumFractionDigits(1);
        float temp = 0f;
        if (allTable != 0) {
            temp = Float.parseFloat(numberFormat.format((float) monitorTable / (float) allTable * 100));
        }
        // 监控覆盖率
        int monitorCoverage = Math.round(temp);

        // 今日问题总数
        Integer problemTotal = this.getProblemTotal(projectId);

        // 去除跨层访问数
        // Integer crossLevelTotal = dataQualityViewMapper.getCrossLevelTotal(projectId);

        float tempDesc = 0f;
        int totalDescCount = descCount + noDescCount;
        if (totalDescCount != 0) {
            tempDesc =
                Float.parseFloat(numberFormat.format((float) descCount / (float) totalDescCount * 100));
        }
        // 表描述信息维护率
        int descRate = Math.round(tempDesc);

        // 数据质量规则数

        long count =
            dataQualityRuleService.count(
                new LambdaQueryWrapper<DataQualityRuleEntity>()
                    .eq(DataQualityRuleEntity::getProjectId, projectId));

        return new DataQualityViewTableDomain(
            problemTotal, (int) count, monitorCoverage, monitorTable, monitorField, descRate);
    }

    @Override
    public DataQualityChartDomain dataQualityChartService(Long projectId) {
        // "数据质量问题表TOP10"
        List<DataQualityViewTopModelDaoDomain> dataQualityViewTopModelDaoDomains =
            this.listProblemTop(projectId);
        List<DataQualityViewTopDomain> problemTopResponse =
            ConvertUtil.copyProperties(
                dataQualityViewTopModelDaoDomains, DataQualityViewTopDomain.class);

        // "数据质量趋势"
        List<DataQualityViewWeekModelDaoDomain> problemTendWeek = this.listProblemTendWeek(projectId);

        List<String> lastSevenDays = listLastSevenDays();
        List<DataQualityTendDomain> dataQualityViewWeekModels = new ArrayList<>();

        for (String date : lastSevenDays) {
            boolean flag = true;
            for (DataQualityViewWeekModelDaoDomain dataQualityViewWeekModel : problemTendWeek) {
                String statisticsDay = dataQualityViewWeekModel.getStatisticsDay();
                if (null != statisticsDay && date.equals(statisticsDay.trim())) {
                    flag = false;
                    dataQualityViewWeekModels.add(
                        new DataQualityTendDomain(date, dataQualityViewWeekModel.getExceptionSum()));
                }
            }
            if (flag) {
                dataQualityViewWeekModels.add(new DataQualityTendDomain(date, 0));
            }
        }

        // 今日质量问题项 默认取前10条
        List<DataQualityTodayExceptionDaoDomain> todayException = this.listTodayException(projectId);

        if (todayException != null && todayException.size() > 10) {
            todayException = todayException.subList(0, 10);
        }

        List<DataQualityTodayExceptionDomain> dataQualityTodayExceptionDomains =
            ConvertUtil.copyProperties(todayException, DataQualityTodayExceptionDomain.class);

        return new DataQualityChartDomain(
            problemTopResponse, dataQualityViewWeekModels, dataQualityTodayExceptionDomains);
    }

    @Override
    public Boolean testData() {
        // 测试测试复杂sql写在这里

    /*    DataQualityStatisticsExceptionEntity dataQualityStatisticsExceptionEntity =
        new DataQualityStatisticsExceptionEntity();
    dataQualityStatisticsExceptionEntity.setCategory(1);
    dataQualityStatisticsExceptionEntity.setProjectId("sdfdsf");
    dataQualityStatisticsExceptionEntity.setExceptionCount(5);
    Date parse = DateUtil.parse("2021-08-18", DateUtil.DATE_PATTERN.yyyyMMdd);
    dataQualityStatisticsExceptionEntity.setStatisticsDay(parse);
    dataQualityStatisticsExceptionMapper.insertOne(dataQualityStatisticsExceptionEntity);*/

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        //    String projectId = "sdfdsf";
        //
        //    List<DataQualityViewWeekModelDaoDomain> dataQualityViewWeekModelDaoDomains =
        //        dataQualityViewMapper.listProblemTendWeek(projectId);
        //    System.out.println(dataQualityViewWeekModelDaoDomains);
        //    List<DataQualityViewDisModelDaoDomain> dataQualityViewDisModelDaoDomains =
        //        dataQualityViewMapper.listProblemDisByDay(projectId);
        //    System.out.println(dataQualityViewDisModelDaoDomains);
        //    List<DataQualityViewDisModelDaoDomain> dataQualityViewDisModelDaoDomains1 =
        //        dataQualityViewMapper.listProblemDisByWeek(projectId);
        //    System.out.println(dataQualityViewDisModelDaoDomains1);
        //    List<DataQualityViewDisModelDaoDomain> dataQualityViewDisModelDaoDomains2 =
        //        dataQualityViewMapper.listProblemDisByMonth(projectId);
        //    System.out.println(dataQualityViewDisModelDaoDomains2);

        return true;
    }

    /**
     * @param projectId
     * @description : 近七天的数据
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public List<DataQualityViewWeekModelDaoDomain> listProblemTendWeek(Long projectId) {
        Calendar c = Calendar.getInstance();
        // 过去七天 7天前的 00：00：00 开始
        c.setTime(new Date());
        c.add(Calendar.DATE, -6);
        Date d = c.getTime();
        String day = format.format(d) + " 00:00:00";
        Date last7day = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        // 首先对7天数据进行过滤
        QueryWrapper<DataQualityStatisticsExceptionEntity> qw = new QueryWrapper<>();
        qw.select("SUM(exception_count) as exceptionSum, statistics_day as statisticsDay");
        qw.eq("project_id", projectId);
        qw.ge("create_time", last7day);
        qw.groupBy("statistics_day");
        qw.orderByDesc("statistics_day");

        List<Map<String, Object>> maps = dataQualityStatisticsExceptionService.listMaps(qw);
        maps.forEach(m -> {
            m.put("statisticsDay", m.get("statisticsday"));
            m.put("exceptionSum", m.get("exceptionsum"));
        });

        // 用fastJson转化一下
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(maps);
        List<DataQualityViewWeekModelDaoDomain> mappedResults =
            jsonArray.toJavaList(DataQualityViewWeekModelDaoDomain.class);

        return mappedResults;
    }

    /**
     * @param projectId
     * @description : top10
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public List<DataQualityViewTopModelDaoDomain> listProblemTop(Long projectId) {
        // top10
        // 今天
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

    /*  SELECT dste.tbl_id,
           dste.tbl_name,
           dste.exception_count,
           dst.security_level
    FROM dataquality_statistics_table_exception dste
             LEFT JOIN data_standard_tbl dst ON dste.tbl_id = dst.tbl_id
    WHERE TO_DAYS(dste.statistics_day) = TO_DAYS(NOW())
      AND dste.project_id = #{projectId}
    ORDER BY dste.exception_count DESC
    LIMIT 10*/

        List<DataQualityStatisticsTableExceptionEntity> multi =
            dataQualityStatisticsTableExceptionService.list(
                new LambdaQueryWrapper<DataQualityStatisticsTableExceptionEntity>()
                    .eq(DataQualityStatisticsTableExceptionEntity::getProjectId, projectId)
                    .ne(DataQualityStatisticsTableExceptionEntity::getExceptionCount, 0)
                    .ge(DataQualityStatisticsTableExceptionEntity::getUpdateTime, today)
                    .orderByDesc(DataQualityStatisticsTableExceptionEntity::getExceptionCount));

        List<DataQualityViewTopModelDaoDomain> dataQualityViewTopModelDaoDomains =
            ConvertUtil.copyProperties(multi, DataQualityViewTopModelDaoDomain.class);

        return dataQualityViewTopModelDaoDomains;
    }

    /**
     * @param projectId
     * @description : 数据质量分布：按日
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public List<DataQualityViewDisModelDaoDomain> listProblemDisByDay(Long projectId) {
        // 今天
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        QueryWrapper<DataQualityStatisticsExceptionEntity> qw = new QueryWrapper<>();
        qw.select("category ,SUM( exception_count ) as exceptionSum");
        qw.eq("project_id", projectId);
        qw.ge("create_time", today);
        qw.groupBy("category");
        qw.orderByAsc("category");

        List<Map<String, Object>> maps = dataQualityStatisticsExceptionService.listMaps(qw);
        maps.forEach(m -> {
            m.put("exceptionSum", m.get("exceptionsum"));
        });

        // 用fastJson转化一下
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(maps);
        List<DataQualityViewDisModelDaoDomain> mappedResults =
            jsonArray.toJavaList(DataQualityViewDisModelDaoDomain.class);

        return mappedResults;
    }

    /**
     * @param projectId
     * @description : 数据质量分布：按周
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public List<DataQualityViewDisModelDaoDomain> listProblemDisByWeek(Long projectId) {
        Calendar c = Calendar.getInstance();
        // 过去七天 7天前的 00：00：00 开始
        c.setTime(new Date());
        c.add(Calendar.DATE, -6);
        Date d = c.getTime();
        String day = format.format(d) + " 00:00:00";
        Date last7day = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        QueryWrapper<DataQualityStatisticsExceptionEntity> qw = new QueryWrapper<>();
        qw.select("category ,SUM( exception_count ) as exceptionSum");
        qw.eq("project_id", projectId);
        qw.ge("create_time", last7day);
        qw.groupBy("category");
        qw.orderByAsc("category");

        List<Map<String, Object>> maps = dataQualityStatisticsExceptionService.listMaps(qw);

        // 用fastJson转化一下
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(maps);
        List<DataQualityViewDisModelDaoDomain> mappedResults =
            jsonArray.toJavaList(DataQualityViewDisModelDaoDomain.class);

        return mappedResults;
    }

    /**
     * @param projectId
     * @description : 数据质量分布：按月
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public List<DataQualityViewDisModelDaoDomain> listProblemDisByMonth(Long projectId) {
        Calendar c2 = Calendar.getInstance();
        // 过去一个月 00：00：00 开始
        c2.setTime(new Date());
        c2.add(Calendar.MONTH, -1);
        Date d2 = c2.getTime();
        String day2 = format.format(d2) + " 00:00:00";
        Date lastMonth = DateUtil.parse(day2, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        QueryWrapper<DataQualityStatisticsExceptionEntity> qw = new QueryWrapper<>();
        qw.select("category ,SUM( exception_count ) as exceptionSum");
        qw.eq("project_id", projectId);
        qw.ge("create_time", lastMonth);
        qw.groupBy("category");
        qw.orderByAsc("category");

        List<Map<String, Object>> maps = dataQualityStatisticsExceptionService.listMaps(qw);

        // 用fastJson转化一下
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(maps);
        List<DataQualityViewDisModelDaoDomain> mappedResults =
            jsonArray.toJavaList(DataQualityViewDisModelDaoDomain.class);

        return mappedResults;
    }

    /**
     * @param projectId
     * @description : 查询表相关的数据（当天00：00：00后产生的数据）
     * @author : tinglan.ys
     * @date : 2022/3/4
     */
    @Override
    public DataQualityViewTableModelDaoDomain getProblemTableInfo(Long projectId) {
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        DataQualityStatisticsMonitorEntity dataQualityStatisticsMonitorEntity =
            dataQualityStatisticsMonitorService.getOne(
                new LambdaQueryWrapper<DataQualityStatisticsMonitorEntity>()
                    .eq(DataQualityStatisticsMonitorEntity::getProjectId, projectId)
                    .ge(DataQualityStatisticsMonitorEntity::getUpdateTime, today));

        // 实体类映射如下
    /*      <result column="table_count" jdbcType="INTEGER" property="monitorTable"></result>
    <result column="total_table_count" jdbcType="INTEGER" property="allTable"></result>
    <result column="field_count" jdbcType="INTEGER" property="monitorField"></result>
    <result column="total_table_desc_count" jdbcType="INTEGER" property="descCount"></result>
    <result column="total_table_no_desc_count" jdbcType="INTEGER" property="noDescCount"></result>*/

        int monitorTable = 0;
        int allTable = 0;
        int monitorField = 0;
        int descCount = 0;
        int noDescCount = 0;

        if (dataQualityStatisticsMonitorEntity != null) {
            // 监控表数
            monitorTable =
                dataQualityStatisticsMonitorEntity.getTableCount() == null
                    ? 0
                    : dataQualityStatisticsMonitorEntity.getTableCount();
            // 总表数
            allTable =
                dataQualityStatisticsMonitorEntity.getTotalTableCount() == null
                    ? 0
                    : dataQualityStatisticsMonitorEntity.getTotalTableCount();
            // 监控字段数
            monitorField =
                dataQualityStatisticsMonitorEntity.getFieldCount() == null
                    ? 0
                    : dataQualityStatisticsMonitorEntity.getFieldCount();
            // 带描述的总条数，表描述算一条，字段描述算一条，包括分区字段
            descCount =
                dataQualityStatisticsMonitorEntity.getTotalTableDescCount() == null
                    ? 0
                    : dataQualityStatisticsMonitorEntity.getTotalTableDescCount();
            // 不带描述的总条数
            noDescCount =
                dataQualityStatisticsMonitorEntity.getTotalTableNoDescCount() == null
                    ? 0
                    : dataQualityStatisticsMonitorEntity.getTotalTableNoDescCount();
        }

        DataQualityViewTableModelDaoDomain dataQualityViewTableModelDaoDomain =
            new DataQualityViewTableModelDaoDomain();
        dataQualityViewTableModelDaoDomain.setMonitorTable(monitorTable);
        dataQualityViewTableModelDaoDomain.setAllTable(allTable);
        dataQualityViewTableModelDaoDomain.setMonitorField(monitorField);
        dataQualityViewTableModelDaoDomain.setDescCount(descCount);
        dataQualityViewTableModelDaoDomain.setNoDescCount(noDescCount);

        return dataQualityViewTableModelDaoDomain;
    }

    /**
     * @param jobId
     * @description : 统计某个任务下的字段执行记录
     * @author : tinglan.ys
     * @date : 2022/3/31
     */
    @Override
    public List<DataQualityJobRuleFieldCustomDaoDomain> getRuleAlarmInfo(Long jobId) {
    /* <select id="getRuleAlarmInfo" resultMap="BaseResultMap2">
        SELECT
            jrf.*,
            j.tbl_id,
            t.tbl_name,
            jr.rule_id,
            r.rule_name
        FROM
            dataquality_job_rule_field jrf
            LEFT JOIN dataquality_job_rule jr ON jrf.dataquality_job_rule_id = jr.id
            LEFT JOIN dataquality_job j ON jr.dataquality_job_id = j.id
            LEFT JOIN data_standard_tbl t ON j.tbl_id = t.tbl_id
            LEFT JOIN dataquality_rule r ON jr.rule_id = r.id
        WHERE
            j.id = #{jobId}
    </select>*/

        // nosql数据库写表链接好烦啊 -_-!
        // 查询数据质量任务
        DataQualityJobEntity dataQualityJobEntity = dataQualityJobService.getById(jobId);
        // 查询规则执行记录

        List<DataQualityJobRuleEntity> dataQualityJobRuleEntities =
            dataQualityJobRuleService.list(
                new LambdaQueryWrapper<DataQualityJobRuleEntity>()
                    .eq(DataQualityJobRuleEntity::getDataqualityJobId, jobId));

        // 查询每个字段的执行记录
        List<Long> allJobRuleIds =
            dataQualityJobRuleEntities.stream()
                .map(dataQualityJobRuleEntity -> dataQualityJobRuleEntity.getId())
                .collect(Collectors.toList());
        List<DataQualityJobRuleFieldEntity> dataQualityJobRuleFieldEntities = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(allJobRuleIds)) {
            dataQualityJobRuleFieldEntities =
                dataQualityJobRuleFieldService.list(
                    new LambdaQueryWrapper<DataQualityJobRuleFieldEntity>()
                        .in(DataQualityJobRuleFieldEntity::getDataqualityJobRuleId, allJobRuleIds));
        }

        List<DataQualityJobRuleFieldCustomDaoDomain> dataQualityJobRuleFieldCustomDaoDomains =
            ConvertUtil.copyProperties(
                dataQualityJobRuleFieldEntities, DataQualityJobRuleFieldCustomDaoDomain.class);
        for (DataQualityJobRuleFieldCustomDaoDomain dataQualityJobRuleFieldCustomDaoDomain :
            dataQualityJobRuleFieldCustomDaoDomains) {
            // 塞入拼上表名，规则名等信息
            dataQualityJobRuleFieldCustomDaoDomain.setTblId(dataQualityJobEntity.getTblId());
            dataQualityJobRuleFieldCustomDaoDomain.setTblName(dataQualityJobEntity.getTblName());

            // 找到对应的ruleId ruleName
            Long dataQualityJobRuleId = dataQualityJobRuleFieldCustomDaoDomain.getDataqualityJobRuleId();
            List<DataQualityJobRuleEntity> collect =
                dataQualityJobRuleEntities.stream()
                    .filter(d -> d.getId().equals(dataQualityJobRuleId))
                    .collect(Collectors.toList());
            // 过滤出来的list只有1条
            dataQualityJobRuleFieldCustomDaoDomain.setRuleId(collect.get(0).getRuleId());
            dataQualityJobRuleFieldCustomDaoDomain.setRuleName(collect.get(0).getRuleName());
        }

        return dataQualityJobRuleFieldCustomDaoDomains;
    }

    /**
     * @param projectId
     * @description : 今天问题统计
     * @author : tinglan.ys
     * @date : 2022/8/29
     */
    @Override
    public Integer getProblemTotal(Long projectId) {
    /* SELECT
    SUM( exception_count ) as exception_count
    FROM
            dataquality_statistics_exception
    WHERE
    TO_DAYS( statistics_day ) = TO_DAYS(NOW())
    AND
    project_id = #{projectId}*/
        // 今天
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        List<DataQualityStatisticsExceptionEntity> multi =
            dataQualityStatisticsExceptionService.list(
                new LambdaQueryWrapper<DataQualityStatisticsExceptionEntity>()
                    .eq(DataQualityStatisticsExceptionEntity::getProjectId, projectId)
                    .ge(DataQualityStatisticsExceptionEntity::getUpdateTime, today));

        Integer totalNum = 0;
        for (DataQualityStatisticsExceptionEntity dataQualityStatisticsExceptionEntity : multi) {
            // 遍历统计所有的问题数字
            totalNum = totalNum + dataQualityStatisticsExceptionEntity.getExceptionCount();
        }
        return totalNum;
    }

    /**
     * @param projectId
     * @description : 今天异常
     * @author : tinglan.ys
     * @date : 2022/8/29
     */
    @Override
    public List<DataQualityTodayExceptionDaoDomain> listTodayException(Long projectId) {
        List<DataQualityTodayExceptionDaoDomain> dataQualityTodayExceptionDaoDomains =
            new ArrayList<>();
        Date date = new Date();
        String day = format.format(date) + " 00:00:00";
        Date today = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);

        List<DataQualityJobEntity> jobs =
            dataQualityJobService.list(
                new LambdaQueryWrapper<DataQualityJobEntity>()
                    .eq(DataQualityJobEntity::getProjectId, projectId)
                    .ge(DataQualityJobEntity::getUpdateTime, today));

        if (CollectionUtils.isEmpty(jobs)) {
            return dataQualityTodayExceptionDaoDomains;
        }

        List<Long> jobIds = jobs.stream().map(j -> j.getId()).collect(Collectors.toList());

        List<DataQualityJobRuleFieldCustomDaoDomain> data = new ArrayList<>();
        for (Long jobId : jobIds) {
            List<DataQualityJobRuleFieldCustomDaoDomain> ruleAlarmInfos = getRuleAlarmInfo(jobId);
            data.addAll(ruleAlarmInfos);
        }

        dataQualityTodayExceptionDaoDomains =
            ConvertUtil.copyProperties(data, DataQualityTodayExceptionDaoDomain.class);

        List<DataQualityTodayExceptionDaoDomain> collect =
            dataQualityTodayExceptionDaoDomains.stream()
                .filter(dq -> dq.getStatus().equals(2) || dq.getStatus().equals(3))
                .collect(Collectors.toList());

        return collect;
    }

    private static List<String> listLastSevenDays() {
        List<String> res = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = DAYS_OF_TEND; i >= 0; i--) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
            Date today = calendar.getTime();
            String result = format.format(today);
            res.add(result);
        }
        return res;
    }

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 过去七天 7天前的 00：00：00 开始
        c.setTime(new Date());
        c.add(Calendar.DATE, -6);
        Date d = c.getTime();
        String day = format.format(d) + " 00:00:00";
        System.out.println("过去七天：" + day);
        Date parse = DateUtil.parse(day, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);
        System.out.println(parse);
        System.out.println("+++++++++++++++++++++++");
        // 今天
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String today = formatter.format(date) + " 00:00:00";
        System.out.println("今天" + today);
        Date parse2 = DateUtil.parse(today, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);
        System.out.println(parse2);
        System.out.println("+++++++++++++++++++++++++");
        // 过去一个月

        Calendar c2 = Calendar.getInstance();
        // 过去一个月 00：00：00 开始
        c2.setTime(new Date());
        c2.add(Calendar.MONTH, -1);
        Date d2 = c2.getTime();
        String day2 = format.format(d2) + " 00:00:00";
        System.out.println("过去一个月：" + day2);
        Date parse3 = DateUtil.parse(day2, DateUtil.DATE_PATTERN.yyyyMMddHHmmss);
        System.out.println(parse3);
        System.out.println("+++++++++++++++++++++++");
    }
}
